package com.niodata.dp.core.resource;

import com.niodata.dp.core.security.ResourceAuthMapper;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component("ResourceManagerImpl")
public class ResourceManagerImpl implements ResourceManager {

  @Autowired
  private ResourceMapper resourceMapper;

  @Autowired
  private ResourceAuthMapper resourceAuthMapper;

  @Transactional
  @Override
  public void saveResource(ResourceDetail resourceDetail) {
    resourceMapper.saveResource(resourceDetail);
  }

  @Override
  public ResourceDetail getResourceDetailById(String id) {
    return resourceMapper.getResourceById(id);
  }

  @Override
  public ResourceDetail getResourceDetailByPath(String path, String type) {
    return resourceMapper.getResourceByPath(path, type);
  }

  @Override
  public List<ResourceDetail> getUserManagedResources(long userid, String type) {
    return resourceMapper.getUserManagedResources(userid, type);
  }

  @Override
  public List<ResourceDetail> getUserViewableResources(long userid, String type) {
    return resourceMapper.getUserViewableResources(userid, type);
  }

  @Override
  public ResourceDetail getExactlyResourceDetailByPathPrefix(String path, String type) {
    List<ResourceDetail> details = this.getResourceDetailsByPathPrefix(path, type);
    if (details == null || details.isEmpty()) {
      return null;
    }
    if (details.size() == 1) {
      return details.get(0);
    }
    ResourceDetail detail = details.get(0);
    for (int i = 1; i < details.size(); i++) {
      ResourceDetail detail1 = details.get(i);
      if (detail1.getPath().length() > detail.getPath().length()) {
        detail = detail1;
      }
    }
    return detail;
  }

  @Override
  public List<ResourceDetail> getResourceDetailsByPathPrefix(String path, String type) {
    return resourceMapper.getResourceByPathPrefix(path, type);
  }

  @Override
  public List<ResourceDetail> getResourceDetailsByPrefix(String path, String type) {
    return resourceMapper.getResourceByPrefix(path, type);
  }

  @Transactional
  @Override
  public void deleteResource(String resId) {
    resourceMapper.deleteResource(resId);
    this.resourceAuthMapper.deleteResAuth(resId, 0, null, null);
  }

  @Transactional
  @Override
  public void updateResource(ResourceDetail resourceDetail) {
    resourceMapper.updateResource(resourceDetail);
  }

  @Transactional
  @Override
  public void deleteResouceByPath(String path, String type) {
    resourceMapper.deleteResourceByPath(path, type);
    this.resourceAuthMapper.deleteResAuthByPath(path, type);
  }

}
